import AuthService from '../../request/auth.service.js'
import {
	UserService
} from '../../request/api-package.js'

// action types
const TYPES = {
	TOKEN: '', //token
	SET_ERROR: 'SET_ERROR', // 错误
	SET_AUTH: 'SET_AUTH', // 用户认证信息
	CLEAR_AUTH: 'CLEAR_AUTH', // 清除认证信息	
};

// initial state
const state = {
	isAuthenticated: false, //状态判断
	user: {},
	errors: null
};

// getters
const getters = {
	currentUser(state) {
		return state.user;
	},
	isAuthenticated(state) {
		return state.isAuthenticated;
	}
};

// mutations
const mutations = {
	[TYPES.SET_ERROR](state, error) {
		state.errors = error;
	},
	[TYPES.SET_AUTH](state, user) {
		state.isAuthenticated = true;
		state.user = user;
		state.errors = {};
		AuthService.set(state.user);
	},
	[TYPES.CLEAR_AUTH](state) {
		state.isAuthenticated = false;
		state.user = {};
		state.errors = {};
		AuthService.logout();
	},
};
// actions
const actions = {
	// 用户登录
	login({
		commit
	}, user = {}) {
		return new Promise((resolve, reject) => {
			UserService.login(user)
				.then((res) => {
					if (res.data.code === 200) {
						commit(TYPES.SET_AUTH, res.data.result.token);
						AuthService.set(res.data.result.token)
						AuthService.setUserinfo({
							info: res.data.result.userInfo,
						})
						// AuthService.index()
						resolve(res);
					} else {
						// console.log('autn', res)
						resolve(res)
					}
				}).catch((res) => {
					commit(TYPES.SET_ERROR, `${res.data.msg}`);
					console.log(res)
					reject(res);
				});
		});
	},

	// 注销
};


export default {
	namespaced: true, //独立命名空间
	state,
	getters,
	actions,
	mutations
};